<template>
  <div>
    <el-upload
      :class="{disabled: isUploaded }"
      action="#"
      :limit="1"
      :http-request="upload"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="changeFile"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress
      v-if="showPercent"
      style="width: 180px"
      :percentage="percent"
    />
    <!-- 预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="showDialog"
    >
      <img
        :src="imageUrl"
        style="width:100%"
        alt=""
      >
    </el-dialog>
  </div>
</template>

<script>
// 导入cos的SDK调用
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID2JMPE1qvDJCmTvdDTqxFgssaAVbRkxoR', // 身份识别 ID
  SecretKey: 'Xw62h4GDwa4JIzUGqKgZyCAzwf9N5f06' // 身份密钥
})
export default {
  data () {
    return {
      imageUrl: '',
      showDialog: false,
      fileList: [],
      showPercent: false,
      percent: 0
    }
  },
  computed: {
    isUploaded () {
      return this.fileList.length === 1
    }
  },
  methods: {
    beforeUpload (file) {
      // 要开始做文件上传的检查了
      // 文件类型 文件大小
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      // 转换M（兆）=》1M=1024KB 1KB=1024B（字节）
      const size = file.size / 1024 / 1024

      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      if (size > 5) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return false
      }
      // 校验通过返回true
      this.showPercent = true
      return true
    },
    // 预览
    preview (file) {
      console.log(file)
      this.imageUrl = file.url
      this.showDialog = true
    },
    handleRemove (file) {
      // file是点击删除的文件
      console.log('del:', file)
      this.fileList = []
    },
    // 文件状态改变时的钩子=》存储文列列表到fileList
    changeFile (file, fileList) {
      console.log('final:', file, fileList, this.fileList)
      // this.fileList = fileList.map(item => item)
      this.fileList = fileList
    },
    // 上传
    upload (params) {
      console.log('start:', params.file, this.fileList)
      cos.putObject({
        Bucket: 'hrsass-1255477649', /* 必须 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log('ok:', err || data, this.fileList)
        if (!err && data.statusCode === 200) {
          console.log('cg:', this.fileList)
          this.fileList.forEach(item => {
            if (item.uid === params.file.uid) {
              // 存储当前上传图片返回的服务器url
              item.url = `http://${data.Location}`
              // 上传完成标记
              item.upload = true
            }
          })
          setTimeout(() => {
            this.showPercent = false // 隐藏进度条
            this.percent = 0 // 进度归0
            console.log(
              'final-p:', this.fileList
            )
          }, 800)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled ::v-deep .el-upload--picture-card {
  display: none;
}
</style>

